/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: MyAuthenticationSuccessHandler
 * @Package com.rx.bean
 * @Description: 成功返回
 * @author: 陈锦韬
 * @date: 2020\5\22 0022
 * @version V1.0
 * @Copyright: 2020 陈锦韬  All rights reserved.
 */
package com.rx.core.bean;

import com.alibaba.fastjson.JSON;
import com.rx.core.base.RxResponse;
import com.rx.core.enm.CERT_ERROR;
import com.rx.core.enm.LOGIN_TYPE;
import com.rx.core.enm.RESULT_CODE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Administrator
 * @Description: 失败返回
 * @date: 2020\5\22 0022
 */
@Component
@Slf4j
public class RxFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        log.info("登录失败");

        //如果是json 格式
        if (LOGIN_TYPE.JSON.equals(LOGIN_TYPE.JSON)){
            //返回json数据
            RxResponse result = null;
            if (e instanceof AccountExpiredException) {
                //账号过期
                result = RxResponse.fail(CERT_ERROR.USER_ACCOUNT_EXPIRED);
            } else if (e instanceof BadCredentialsException) {
                //密码错误
                result = RxResponse.fail(CERT_ERROR.USER_CREDENTIALS_ERROR);
            } else if (e instanceof CredentialsExpiredException) {
                //密码过期
                result = RxResponse.fail(CERT_ERROR.USER_CREDENTIALS_EXPIRED);
            } else if (e instanceof DisabledException) {
                //账号不可用
                result = RxResponse.fail(CERT_ERROR.USER_ACCOUNT_DISABLE);
            } else if (e instanceof LockedException) {
                //账号锁定
                result = RxResponse.fail(CERT_ERROR.USER_ACCOUNT_LOCKED);
            } else if (e instanceof InternalAuthenticationServiceException) {
                //用户不存在
                result = RxResponse.fail(CERT_ERROR.USER_ACCOUNT_NOT_EXIST);
            }else{
                //其他错误
                result = new RxResponse(RESULT_CODE.FAIL.getCode(),e.getMessage());
            }
            //处理编码方式，防止中文乱码的情况
            response.setContentType("text/json;charset=utf-8");
            //塞到HttpServletResponse中返回给前台
            response.getWriter().write(JSON.toJSONString(result));

        }else{
            //如果不是json格式，返回view
            super.onAuthenticationFailure(request,response,e);
        }

    }

}
